import logging, random, os
import Cookie, re, datetime, calendar, email.utils

from google.appengine.ext   import webapp
from google.appengine.ext.webapp import template

from utils                  import *
from app_settings           import *

ROOT_PATH = os.path.dirname(__file__)
TEMPLATE = os.path.join(ROOT_PATH, 'templates')

class LP(webapp.RequestHandler):
    def get(self, password):
        logging.debug('GET request received, calling POST...')
        self.post(password)

    def post(self,password):
        logging.debug('POST request received.')
        current_host = self.request.host
        current_path = self.request.path_info_peek()
        current_file = self.request.path.split('/')[2]
        
        if current_host in bad_domains:
            logging.debug('found [%s] in bad_doamins' % current_host)
            new_host = good_domains[random.randint(0, len(good_domains)-1)]
            logging.debug('redirect to [%s%s]' % (new_host, current_path))
            self.redirect(self.request.scheme+'://'+new_host+current_path)

        if should_I_set_cookie(self.request):
            password = get_random_password(random.randint(2,4))
            logging.debug('setting cookie')
            self.response.headers.add_header('Set-Cookie',
                    get_cookie_string(
                        name = 'nomad',
                        value = 'yeah',
                        expires_days = 1))
            self.redirect(self.request.scheme+'://'+current_host+
                    '/'+current_path+'/like%s.html' % password)
        
        page_path = os.path.join(TEMPLATE, 'index.html')

        shareurl = shareurls[random.randint(0, len(shareurls)-1)]
        shareimage = shareimages[random.randint(0, len(shareimages)-1)]
        initial_video = videos[0]
        if (len(videos)>1):
            playlist = "&playlist="
            for i in range(1, len(videos)):
                if i>1:
                    playlist=playlist+','
                playlist=playlist+videos[i]
        else:
            playlist = "&playlist=%s" % initial_video

        if using_mobile_share:
            fb_share_url = 'http://m.facebook.com/sharer.php?u=%(shareurl)s&t=%(title)s' % {
                    'title': title,
                    'shareurl': shareurl}
        else:
            fb_share_url = 'http://www.facebook.com/sharer.php?s=100&p[title]=%(title)s&p[summary]=%(sharedesc)s %(shareurl)s&p[url]=%(shareurl)s&p[images][0]=%(shareimage)s' % {
                    'host':current_host,
                    'mydir':current_path,
                    'fname':current_file,
                    'offerlink': offerlink,
                    'shareurl': shareurl,
                    'title': title,
                    'sharedesc': sharedesc,
                    'shareimage': shareimage
        }

        template_values = {
                'host':current_host,
                'mydir':current_path,
                'fname':current_file,
                'shareimage': shareimage,
                'offerlink': offerlink,
                'shareurl': shareurl,
                'title': title,
                'sharedesc': sharedesc,
                'coupon_id': get_random_password(6),
                'initial_video': initial_video,
                'playlist': playlist,
                'fb_share_url': fb_share_url,
                'date_now': datetime.datetime.now()
                }
        return self.response.out.write(template.render(page_path, template_values))

def should_I_set_cookie(request):
    logging.debug('check if should set cookie')
    result = False
    if request.headers.get('HTTP_REFERER', ''):
        if 'facebook' in request.headers['HTTP_REFERER'].lower():
            result = True
    if request.query_string:
        result = True
    if result and request.cookies.get('nomad', ''):
        result = False

    return result

def get_cookie_string(name,value,domain=None,expires=None,
        path="/",expires_days=None):
    """Sets the given cookie name/value with the given options."""
    logging.debug('generating cookie string')
    if re.search(r"[\x00-\x20]",name + value): # Don't let us accidentally inject bad stuff
        raise ValueError("Invalid cookie %r:%r" % (name,value))
    new_cookie = Cookie.BaseCookie()
    new_cookie[name] = value
    if domain:
        new_cookie[name]["domain"] = domain
    if expires_days is not None and not expires:
        expires = datetime.datetime.utcnow() + datetime.timedelta(days=expires_days)
    if expires:
        timestamp = calendar.timegm(expires.utctimetuple())
    new_cookie[name]["expires"] = email.utils.formatdate(timestamp,localtime=False,usegmt=True)
    if path:
        new_cookie[name]["path"] = path
    return new_cookie[name].OutputString(None)
